<template>
  <el-row>
    <el-col :span="6">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <el-input v-model="filterText" placeholder="输入关键字过滤"/>
            <el-tree
              ref="tree"
              class="filter-tree"
              :data="treedata"
              :props="defaultProps"
              default-expand-all
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              @node-click="nodeClick"></el-tree>
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="18">
      <basic-container>
        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="data"
                   :page="page"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   v-model="form"
                   ref="crud"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   @row-del="rowDel"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   @on-load="onLoad">
          <template slot="menuLeft">
            <el-button type="danger"
                       size="small"
                       icon="el-icon-delete"
                       plain
                       v-if="permission.rtcoperator_delete"
                       @click="handleDelete">删 除
            </el-button>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button v-show="scope.row.operatorId == null" type="text" size="small" icon="el-icon-connection" @click.stop="handleBind(scope.row)" title="是指和该系统用户进行绑定">绑定</el-button>
            <el-button v-show="scope.row.operatorId == null" type="text" size="small" icon="el-icon-full-screen" @click.stop="handleCode(scope.row)" title="是指和小程序接警员进行绑定">扫码</el-button>
            <el-button v-show="scope.row.operatorId != null" type="text" size="small" icon="el-icon-full-screen" @click.stop="unBind(scope.row)">解绑</el-button>
          </template>
        </avue-crud>
        <el-dialog title="请选择通讯录人员" append-to-body :visible.sync="userBox">
          <el-table border stripe :data="dataUser">
            <el-table-column prop="username" label="登录账号" align="center"></el-table-column>
            <el-table-column prop="nickName" label="用户昵称" align="center"></el-table-column>
            <el-table-column prop="realName" label="用户姓名" align="center"></el-table-column>
            <el-table-column prop="seatId" label="坐席号" align="center"></el-table-column>
            <el-table-column prop="seatName" label="坐席名称" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="200">
              <template slot-scope="scope">
                <el-button v-if="scope.row.bindStatus == 0" type="primary" size="small" icon="el-icon-connection" @click="handleBindB(scope.row)">绑定</el-button>
                <el-button v-if="scope.row.bindStatus == 1" type="text" size="small" icon="el-icon-connection" style="color: #e80b0b">已绑定</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination :current-page="curPageUserPage" :page-size="limitUserPage" layout="total, prev, pager, next" :total="totalUserPage" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
          <span slot="footer" class="dialog-footer">
            <el-button @click="userBox = false">取 消</el-button>
          </span>
        </el-dialog>
        <div class="qr-mask" v-show="qrcodeShow">
          <div class="qr-box">
            <i class="el-icon-close" @click="closeQrCode"></i>
            <p class="title">请扫码</p>
            <div id="qrcode" ref="qrcode"></div>
          </div>
        </div>
      </basic-container>
    </el-col>
  </el-row>
</template>

<script>
  import {getPage, getDetail, add, update, remove, bind, token, userPage, unBind} from "@/api/bureau/miniaccident/rtcoperator";
  import {mapGetters} from "vuex";
  import {getTree} from "@/api/bureau/miniaccident/rtcseat";
  import QRCode from "qrcodejs2";
  // import { userPage } from "@/api/system/user";

  export default {
    data() {
      return {
        curPageUserPage: 1,
        limitUserPage: 10,
        totalUserPage: 0,
        userBox: false,
        defaultProps: {
          children: 'children',
          label: 'seatName'
        },
        qrcodeShow: false,
        treedata: [],
        form: {},
        query: {},
        loading: true,
        filterText: '',
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: false,
          viewBtn: false,
          selection: true,
          // defaultSort:{prop:'sort',order:'aescending'},
          column: [
            {
              label: "序号",
              prop: "sort",
              type: "number",
              hide: true,
              rules: [{
                required: false,
                message: "请输入序号",
                trigger: "blur"
              }]
            },
            {
              label: "警号",
              prop: "account",
              rules: [{
                required: true,
                message: "请输入警号",
                trigger: "blur"
              }]
            },
            {
              label: "昵称",
              prop: "name",
              rules: [{
                required: false,
                message: "请输入昵称",
                trigger: "blur"
              }]
            },
            {
              label: "手机",
              prop: "phone",
              rules: [{
                required: false,
                message: "请输入手机",
                trigger: "blur"
              }]
            },
            {
              label: "权重",
              prop: "weight",
              rules: [{
                required: false,
                message: "请输入权重",
                trigger: "blur"
              }]
            },
            {
              label: "状态",
              prop: "status",
              rules: [{
                required: false,
                message: "请输入状态",
                trigger: "blur"
              }]
            },
            {
              label: "接警员编号",
              prop: "operatorId",
              disabled: true,
              addDisplay: false,
            },
            {
              label: "坐席名称",
              prop: "seatId",
              type: "tree",
              dicData: [],
              slot: true,
              defaultExpandAll: true,
              props: {
                label: "seatName",
                value: "id",
                children: "children"
              },
              rules: [{
                required: true,
                message: "请输入坐席号",
                trigger: "blur"
              }]
            },
            {
              label: "接警类型",
              prop: "typeName",
              disabled: true,
            },
          ]
        },
        data: [],
        dataUser: [],
        accidentUserId: null,
      };
    },
    watch: {
      'form.tenantId'() {
        if (this.form.tenantId !== '') {
          getTree(this.form.tenantId).then(res => {
            const column = this.findObject(this.option.column, "seatId");
            column.dicData = res.data.data;
          });
        }
      },
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.rtcoperator_add, false),
          viewBtn: this.vaildData(this.permission.rtcoperator_view, false),
          delBtn: this.vaildData(this.permission.rtcoperator_delete, false),
          editBtn: this.vaildData(this.permission.rtcoperator_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          getPage(this.page.currentPage, this.page.pageSize, {seatId: this.query.seatId}).then(res => {
            const data = res.data;
            this.page.total = data.count;
            this.data = data.data;
            this.loading = false;
          });
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return remove(this.ids);
        }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
      },
      handleBind(row){
        userPage(this.curPageUserPage, this.limitUserPage).then(resuser => {
          this.dataUser = resuser.data.data;
          this.totalUserPage = resuser.data.count;
          this.userBox = true;
          this.accidentUserId = row.id;
        });
      },
      handleBindB(row) {
        token(this.accidentUserId).then(restoken => {
          bind({
            id: this.accidentUserId,
            token: restoken.data.data.token,
            operatorId: row.id
          }).then(resbind => {
            this.refreshChange();
            userPage(this.curPageUserPage, this.limitUserPage).then(resuser => {
              this.dataUser = resuser.data.data;
              this.totalUserPage = resuser.data.count;
            });
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          })
        });
      },
      unBind(row) {
        console.log("----->", row.operatorId);
        unBind({
          id: row.id,
          operatorId: row.operatorId
        }).then(resbind => {
          this.refreshChange();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })

        /*unBind({
          id: this.accidentUserId
        }).then(resbind => {
          userPage(this.curPageUserPage, this.limitUserPage).then(resuser => {
            this.dataUser = resuser.data.data;
            this.totalUserPage = resuser.data.count;
          });
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })*/
      },
      handleCode(row) {
        this.qrcodeShow = true;
        let that = this;
        token(row.id).then(restoken => {
          that.$refs.qrcode.innerHTML = "";
          let qrcode = new QRCode("qrcode", {
            width: 220,
            height: 220,
            text: JSON.stringify({
              id: row.id,
              token: restoken.data.data.token
            }),
            colorDark: "#000",
            colorLight: "#fff"
          });
        });
      },
      closeQrCode() {
        this.qrcodeShow = false;
      },
      beforeOpen(done, type) {
        if (["add"].includes(type)) {
          this.form.seatId = this.query.seatId;
        }
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      handleSizeChange(val) {
        this.limitUserPage = val;
        userPage(this.curPageUserPage, this.limitUserPage).then(resuser => {
          this.dataUser = resuser.data.data;
          this.totalUserPage = resuser.data.count;
        });
      },
      handleCurrentChange(val) {
        this.curPageUserPage = val;
        userPage(this.curPageUserPage, this.limitUserPage).then(resuser => {
          this.dataUser = resuser.data.data;
          this.totalUserPage = resuser.data.count;
        });
      },
      nodeClick(data, node, item) {
        this.query.seatId = data.id;
        getPage(this.page.currentPage, this.page.pageSize, {seatId: data.id}).then(res => {
          const data = res.data;
          this.page.total = data.count;
          this.data = data.data;
          this.loading = false;
        });
      },
      refreshChange() {
        getPage(this.page.currentPage, this.page.pageSize, {seatId: this.query.seatId}).then(res => {
          const data = res.data;
          this.page.total = data.count;
          this.data = data.data;
          this.loading = false;
        });
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getTree().then(resTree => {
          let _resTree = resTree.data.data;
          const column = this.findObject(this.option.column, "seatId");
          column.dicData = _resTree;
          this.treedata = _resTree;
          if(_resTree.length > 0) {
            this.query.seatId = _resTree[0].id;
            getPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
              this.page.total = res.data.count;
              this.data = res.data.data;
              this.selectionClear();
            });
          }
        });
        this.loading = false;
      }
    }
  };
</script>

<style scoped lang="scss">
.qr-mask {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 5;
  background-color: rgba(0, 0, 0, 0.6);
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;

  .qr-box{
    position: relative;
    .el-icon-close {
      font-size: 30px;
      cursor: pointer;
      color: #fff;
      position: absolute;
      right: -30px;
      top: -20px;
    }
  }

  .title {
    font-size: 26px;
    color: #fff;
    text-align: center;
  }

  #qrcode {
    width: 240px;
    height: 240px;
    background: #fff;
    padding: 10px;
    ::v-deep img {  //https://blog.csdn.net/qq_38143787/article/details/105566316
      width: 100%;
    }
  }
}

.el-pagination {
  text-align: center;
  margin: 20px 0;
}
</style>
